#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <stdbool.h>

typedef struct
{
    uint32_t x;
    uint32_t y;
} STPoint;

typedef struct
{
    STPoint p;
    uint32_t width;
    uint32_t height;
} STRect;

typedef struct {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    uint8_t alpha;
} STColor;

typedef struct {
    STPoint i;
    int key;
} STKeyEvent;

typedef enum {
    WND_TYPE_BASE,
    WND_TYPE_LABEL,
    WND_TYPE_BUTTON
} EMWndType;

// 窗口状态标志位定义（示例）
typedef enum {
    WND_STATE_VISIBLE   = 0x0001,  // 窗口可见
    WND_STATE_ENABLED   = 0x0002,  // 窗口可交互
    WND_STATE_FOCUSED   = 0x0004,  // 窗口拥有焦点
    WND_STATE_ACTIVE    = 0x0008,  // 窗口处于激活状态（如当前标签页）
    WND_STATE_SELECTED  = 0x0010,  // 窗口被选中（如列表项）
    WND_STATE_INVALID   = 0x0020,  // 数据非法（如输入错误）
    WND_STATE_LOADING   = 0x0040,  // 数据加载中
    WND_STATE_MODAL     = 0x0080,  // 模态窗口（阻塞其他操作）
} WndStateFlags;

typedef enum {
    WND_STATUS_DISABLED,
    WND_STATUS_NORMAL,
    WND_STATUS_,
} EMWndStatus;

typedef struct STWnd STWnd;
typedef struct
{
    void (*OnInit)(STWnd *wnd);
    void (*OnDestroy)(STWnd *wnd);
    void (*OnPaint)(STWnd *wnd);
    void (*OnEvent)(STWnd *wnd, STKeyEvent ev);
} STWndVApi;

typedef struct
{
    void (*DrawPixelAtPos)(STPoint, STColor);
    void (*DrawLine)(STPoint, STPoint, STColor);
    void (*SetBgColor)(STColor);
    void (*SetFgColor)(STColor);
} STDrawDriver;

struct STWnd
{
    uint32_t id;            // 自动生成的唯一ID
    EMWndType type;
    STWnd *parent;
    STWnd *pre;
    STWnd *next;

    STWnd *firstChild;
    STWnd *lastChild;
    
    uint32_t state;                // 状态标志位
    void (*OnStateChanged)(STWnd* wnd, uint32_t old_state); // 状态变化回调
    const STWndVApi *vApi;
};

// 设置状态（按位或）
void WndSetState(STWnd* wnd, uint32_t flags) {
    if (!wnd) return;
    uint32_t old = wnd->state;
    wnd->state |= flags;
    if (wnd->state != old && wnd->OnStateChanged) {
        wnd->OnStateChanged(wnd, old);
    }
}

// 清除状态（按位与取反）
void WndClearState(STWnd* wnd, uint32_t flags) {
    if (!wnd) return;
    uint32_t old = wnd->state;
    wnd->state &= ~flags;
    if (wnd->state != old && wnd->OnStateChanged) {
        wnd->OnStateChanged(wnd, old);
    }
}

// 检查是否包含某状态
bool WndHasState(STWnd* wnd, uint32_t flags) {
    return wnd && (wnd->state & flags) == flags;
}

// 标签组件特有属性
typedef struct {
    STWnd base;           // 必须作为第一个成员
    char* text;
    STColor textColor;
    // STFont* font;
    void (*SetText)(STWnd*, const char*);
    void (*SetTextColor)(STWnd*, STColor);
} STLabel;

// 按钮组件特有属性
typedef struct {
    STWnd base;
    void (*onClickHandler)(STWnd*);
    void (*SetClickHandler)(STWnd*, void (*)(STWnd*));
    STColor hoverColor;
} STButton;

typedef enum {
    WND_OK,
    WND_ERR_NULL_PTR,
    WND_ERR_CYCLE,
    WND_ERR_ALREADY_CHILD,
    WND_ERR_NOT_FOUND
} WndResult;

// ID生成器（简化版）
static uint32_t g_wnd_id_base = 1000;  // ID起始值

static STDrawDriver* g_driver = NULL;

void WndSetGlobalDriver(STDrawDriver* driver) {
    g_driver = driver;
}

STDrawDriver* WndGetGlobalDriver() {
    assert(g_driver && "Driver not initialized!");
    return g_driver;
}


void Label_OnInit(STWnd *wnd){
    printf("Label_OnInit\n");
}
void Label_OnDestroy(STWnd *wnd){
    printf("Label_OnDestroy\n");
}
void Label_OnPaint(STWnd *wnd){
    printf("Label_OnPaint\n");
}
void Label_SetText(STWnd* wnd, const char* text);
void Label_OnEvent(STWnd *wnd, STKeyEvent ev){}
// 标签创建函数
STLabel* CreateLabel(const char* text) {
    static const STWndVApi labelVtbl = {
        .OnInit = Label_OnInit,
        .OnDestroy = Label_OnDestroy,
        .OnPaint = Label_OnPaint,
        .OnEvent = Label_OnEvent
    };

    STLabel* label = calloc(1, sizeof(STLabel));
    label->base.type = WND_TYPE_LABEL;
    label->base.vApi = &labelVtbl;
    label->text = strdup(text);
    label->SetText = Label_SetText;

    if (label->base.vApi->OnInit) {
        label->base.vApi->OnInit((STWnd*)label);
    }
    return label;
}


void Button_OnInit(STWnd *wnd){
    printf("Button_OnInit\n");
}
void Button_OnDestroy(STWnd *wnd){
    printf("Button_OnDestroy\n");
}
void Button_OnPaint(STWnd *wnd){
    printf("Button_OnPaint\n");
}
void Button_OnEvent(STWnd *wnd, STKeyEvent ev){}
void Button_SetClickHandler(STWnd*, void (*)(STWnd*));
// 按钮创建函数
STButton* CreateButton(void (*handler)(STWnd*)) {
    static const STWndVApi btnVtbl = {
        .OnInit = Button_OnInit,
        .OnDestroy = Button_OnDestroy,
        .OnPaint = Button_OnPaint,
        .OnEvent = Button_OnEvent
    };

    STButton* btn = calloc(1, sizeof(STButton));
    btn->base.type = WND_TYPE_BUTTON;
    btn->base.vApi = &btnVtbl;
    btn->onClickHandler = handler;

    btn->SetClickHandler = Button_SetClickHandler;
    if (btn->base.vApi->OnInit) {
        btn->base.vApi->OnInit((STWnd*)btn);
    }
    return btn;
}

// 标签操作接口
void Label_SetText(STWnd* wnd, const char* text) {
    assert(wnd->type == WND_TYPE_LABEL);
    STLabel* label = (STLabel*)wnd;
    const STWndVApi* vtbl = (const STWndVApi*)wnd->vApi;
    
    free(label->text);
    label->text = strdup(text);
    
    // 触发重绘
    if (vtbl->OnPaint) {
        vtbl->OnPaint(wnd);
    }
}

// 按钮操作接口
void Button_SetClickHandler(STWnd* wnd, void (*handler)(STWnd*)) {
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton* btn = (STButton*)wnd;
    const STWndVApi* vtbl = (const STWndVApi*)wnd->vApi;
    
    btn->onClickHandler = handler;
}
void WndRemoveFromParent(STWnd* child);


STWnd* WndCreate(EMWndType type, const STWndVApi* vApi) 
{
    STWnd* wnd = (STWnd*)malloc(sizeof(STWnd));
    if (!wnd) return NULL;
    
    // 自动生成ID（原子操作保证线程安全）
    wnd->id = __sync_fetch_and_add(&g_wnd_id_base, 1);
    
    // 初始化其他成员
    wnd->type = type;
    wnd->parent = NULL;
    wnd->state = 0;
    wnd->pre = wnd->next = NULL;
    wnd->firstChild = wnd->lastChild = NULL;
    wnd->vApi = vApi;
    
    // 初始化回调
    if (wnd->vApi && wnd->vApi->OnInit) {
        wnd->vApi->OnInit(wnd);
    }
    return wnd;
}

int WndIsInSubtree(STWnd *root, STWnd *target) {
    if (!root) return 0;
    if (root == target) return 1;
    for (STWnd *child = root->firstChild; child; child = child->next) {
        if (WndIsInSubtree(child, target)) return 1;
    }
    return 0;
}

WndResult WndAddChild(STWnd *parent, STWnd *child)
{
    if (!parent || !child)
        return WND_ERR_NULL_PTR;
    if (child->parent == parent)
        return WND_ERR_ALREADY_CHILD;

    // 检测循环引用
    STWnd *ancestor = parent;
    while (ancestor) {
        if (ancestor == child)
            return WND_ERR_CYCLE;
        ancestor = ancestor->parent;
    }

    WndRemoveFromParent(child);

    child->parent = parent;
    if (!parent->firstChild) {
        parent->firstChild = child;
        parent->lastChild = child;
    } else {
        parent->lastChild->next = child;
        child->pre = parent->lastChild;
        parent->lastChild = child;
    }
    return WND_OK;
}

void WndRemoveFromParent(STWnd* child) {
    if (!child || !child->parent) return;
    STWnd* parent = child->parent;
    
    if (child->pre)
        child->pre->next = child->next;
    else
        parent->firstChild = child->next;
    
    if (child->next)
        child->next->pre = child->pre;
    else
        parent->lastChild = child->pre;
    
    child->parent = NULL;
    child->pre = NULL;
    child->next = NULL;
}

void WndDestroy(STWnd* wnd) {
    if (!wnd) return;
    printf("wnd des\n");
}

// 递归查找实现
static STWnd* WndFindByIdRecursive(STWnd* wnd, uint32_t target_id)
{
    if (!wnd) return NULL;
    
    // 当前节点匹配
    if (wnd->id == target_id) {
        return wnd;
    }
    
    // 深度优先遍历子节点
    STWnd* child = wnd->firstChild;
    while (child) {
        STWnd* found = WndFindByIdRecursive(child, target_id);
        if (found) return found;
        child = child->next;
    }
    return NULL;
}

// 公开查找接口
WndResult WndFindById(STWnd* root, uint32_t target_id, STWnd** result)
{
    if (!root || !result) return WND_ERR_NULL_PTR;
    
    *result = WndFindByIdRecursive(root, target_id);
    return *result ? WND_OK : WND_ERR_NOT_FOUND;
}

// 重置ID生成器（慎用！）
void WndResetIdSystem(uint32_t new_base_id)
{
    g_wnd_id_base = new_base_id;
}

// 定义回调函数类型
typedef void (*WndCallback)(STWnd* wnd);

// 通用树遍历函数（前序遍历）
void WndTraverse(STWnd* root, WndCallback callback)
{
    if (!root || !callback) return;
    
    // 处理当前节点
    callback(root);
    
    // 递归处理子节点
    STWnd* child = root->firstChild;
    while (child) {
        STWnd* next = child->next;
        WndTraverse(child, callback);
        child = next;
    }
}

// 后序遍历销毁专用
static void WndDestroyTraverse(STWnd* root, WndCallback callback)
{
    if (!root || !callback) return;
    
    // 先处理子节点
    STWnd* child = root->firstChild;
    while (child) {
        STWnd* next = child->next;
        WndDestroyTraverse(child, callback);
        child = next;
    }
    
    // 最后处理当前节点
    callback(root);
}

// 渲染回调函数
static void RenderCallback(STWnd* wnd)
{
    const STWndVApi* vtbl = wnd->vApi;
    if (vtbl && vtbl->OnPaint) {
        vtbl->OnPaint(wnd);
    }
}

// 销毁回调函数
static void DestroyCallback(STWnd* wnd)
{
    const STWndVApi* vtbl = wnd->vApi;
    if (vtbl && vtbl->OnDestroy) {
        vtbl->OnDestroy(wnd);
    }
    free(wnd);
}

// 公开接口
void WndRenderTree(STWnd* root)
{
    WndTraverse(root, RenderCallback);
}

void WndDestroyTree(STWnd* root)
{
    WndDestroyTraverse(root, DestroyCallback);
}

// // 非递归遍历实现（避免栈溢出）
// void WndTraverseIterative(STWnd* root, WndCallback callback)
// {
//     Stack* stack = stack_create();
//     stack_push(stack, root);
    
//     while (!stack_empty(stack)) {
//         STWnd* current = stack_pop(stack);
//         callback(current);
        
//         // 反向压栈保证遍历顺序
//         STWnd* child = current->lastChild;
//         while (child) {
//             stack_push(stack, child);
//             child = child->pre;
//         }
//     }
    
//     stack_destroy(stack);
// }


static const STWndVApi root_vapi = {
    .OnInit = Label_OnInit,
    .OnDestroy = Label_OnDestroy,
    .OnPaint = Label_OnPaint,
    .OnEvent = Label_OnEvent
};

void handle(STWnd *wnd){

}
int main()
{
    STWnd* root = WndCreate(WND_TYPE_BASE, &root_vapi);
    STLabel* l = CreateLabel("123");
    STButton* b = CreateButton(handle);
    WndAddChild(root, &(l->base));
    WndAddChild(root, &(b->base));
    WndRenderTree(root);
    WndDestroyTree(root);
    return 0;
}